package com.coderg.gmall.web.controller;

import com.coderg.gmall.item.feign.ItemPageFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 商品详情页的控制层
 */
@Controller
@RequestMapping(value = "/page/item")
public class ItemController {

    @Autowired
    private ItemPageFeign itemPageFeign;

    /**
     * 打开商品详情页
     * @param skuId
     * @param model
     * @return
     */
    @GetMapping
    public String item(Long skuId, Model model){
        //远程调用
        Map result = itemPageFeign.getItemInfo(skuId);
        //存储数据
        model.addAllAttributes(result);
        //打开页面
        return "item";
    }

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 为商品生成静态页面
     * @param skuId
     * @return
     */
    @GetMapping(value = "/createHtml")
    @ResponseBody
    public String createHtml(Long skuId){
        try {
            //远程调用
            Map result = itemPageFeign.getItemInfo(skuId);
            //声明文件对象
            File file = new File("D:\\java0828", skuId + ".html");
            //声明输出对象
            PrintWriter printWriter = new PrintWriter(file, "UTF-8");
            //构建一个数据容器
            Context context = new Context();
            context.setVariables(result);
            //生成静态页面
            /**
             * redis.call('get', "getPrice:1")
             * 1.模板是哪个
             * 2.数据容器
             * 3.文件保存到哪里去
             */
            templateEngine.process("itemTemplate", context, printWriter);
            //关闭输出流
            printWriter.flush();
            printWriter.close();
            //返回结果
            return "生成成功!";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "生成失败,请重试!";
    }
}
